package IO;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

public class Demo7 {
    private static void scan(File currentFile, String key) {
        if (!currentFile.isDirectory()) {
            return;
        }
        File[] files = currentFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }

        for (File f : files) {
            if (f.isFile()) {
                doSearch(f,key);
            } else {
                scan(f,key);
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径: ");
        String currentPath = scanner.next();
        File currentFile = new File(currentPath);
        if (!currentFile.isDirectory()) {
            System.out.println("路径输入有误!");
            return;
        }
        System.out.println("请输入要搜索的内容关键词: ");
        String key = scanner.next();

        scan(currentFile,key);
    }

    private static void doSearch(File f,String key) {
        //打开文件,读取文件内容,判定内容是否含有key
        StringBuilder stringBuilder = new StringBuilder();

        try (Reader reader = new FileReader(f)) {
            char[] buffer = new char[1024];
            while (true) {
                int n = reader.read(buffer);
                if (n == -1) {
                    break;
                }
                //将缓冲区内容转换为字符串
                String s = new String(buffer,0,n);
                //向stringBuilder追加该字符串
                stringBuilder.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (stringBuilder.indexOf(key) == -1) {
            //未找到
            return;
        }
        //找到了
        System.out.println("找到对应文件: " + f.getAbsolutePath());
    }
}
